package com.demo.collector.util.security;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 沈伟峰
 */
public class TokenUtil {

    private static final long EXPIRED_TIME = 60 * 60 * 1000;
    private static final String SECRET_KEY = "we35nhjkd7kfir9fdregb32n348mz67b";

    public static String generateToken(int uid, String username) {
        Date date = new Date(System.currentTimeMillis() + EXPIRED_TIME);
        Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY);
        Map<String, Object> header = new HashMap<>(2);
        header.put("typ", "JWT");
        header.put("alg", "HS256");

        return JWT.create()
            .withHeader(header)
            .withClaim("uid", uid)
            .withClaim("username", username)
            .withExpiresAt(date)
            .sign(algorithm);
    }

    public static Map<String, Claim> parseToken(String token) {
        return decodeToken(token).getClaims();
    }

    public static boolean verifyToken(String token) {
        try {
            DecodedJWT jwt = decodeToken(token);
            return true;
        } catch (Exception exception) {
            return false;
        }
    }

    private static DecodedJWT decodeToken(String token) {
        Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY);
        JWTVerifier jwtVerifier = JWT.require(algorithm).build();
        return jwtVerifier.verify(token);
    }
}
